//
// See the file COPYING for redistribution information.
//

#include <iostream>
#include <Naipax.hpp>

using namespace std;
using namespace Naipax;

void TestHttpRequest() {
    HttpRequest Req;
    Req.UserAgent() = "blahblahAgent";
    Req.Build("some.host.com", "/somepath/some.cgi?key=value");
    cout << "Request headers: " << "[" << Req.Headers() << "]" << endl;
    Req.Reset();
}

void TestHttpResponse() {
    char Headers[] = "HTTP/1.1 200 OK\n"
        "Cache-Control: no-cache\n"
        "Pragma: no-cache\n"
        "Content-Type: text/html; charset=UTF-8\n"
        "Content-Length: 26\n"
        "Transfer-Encoding: chunked\n"
        "Server: GFE/1.3\n"
        "Date: Fri, 27 Jul 2007 03:24:16 GMT\n"
        "\n"
        "21\n"
        "Here comes the first message body\n"
        "23\n"
        "\nHere comes the second message body\n"
        "0\n";

    cout << "Response Headers: [" << endl << Headers << "]" << endl;

    HttpResponse Res(Headers);
    Res.ParseStatusLine();
    
    cout << "Status: " << Res.mStatus << endl;

    Res.ParseHeaders();
    cout << " -- Parsed Response -- " << endl;
    cout << "Server: " << Res.mServer << endl;
    cout << "MediaType: " << Res.mMediaType << endl;
    cout << "Character Set: " << Res.mCharset << endl;
    cout << "Has ContentLength? " << Res.mHasContentLength << endl;
    cout << "Is chunked transfer? " << Res.mIsChunkedTransfer << endl;
    cout << "Is gzipped? " << Res.mIsGzipped << endl;
    cout << "ContentLength: " << Res.mContentLength << endl;
        
    cout << "Date String: " << Res.mDateStr << endl;
    cout << "Re-rendered Date String: " << ctime(&(Res.mDate)) << endl;
    if (Res.mOtherHeaders.size()) {
        cout << "Other headers: " << endl;
        for (map<string, string>::iterator
                 HeaderIter = Res.mOtherHeaders.begin();
             HeaderIter != Res.mOtherHeaders.end(); HeaderIter++) {
            cout << (*HeaderIter).first
                 << " => " << (*HeaderIter).second << endl;
        }
    }
    cout << "[Body]: " << string(Res.mRespStr, Res.mBodyStartPos) << endl;

    Res.RestoreBody();
    cout << "[Restored body]: " << string(Res.mRespStr, Res.mBodyStartPos) << endl;
    cout << endl << "[The whole response string]: " << Res.mRespStr << endl;
}

int main() {
    cerr << "Test for the Http module" << endl;

    try {
        TestHttpRequest();
        TestHttpResponse();
    }
    catch (Naipax::Error &E) {
        NAIPAX_PERROR(E.What());
        return -1;
    }
    return 0;
}
